from django.core.urlresolvers import reverse
from django.db import transaction
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext

from projects.models import Project
from events.models import Milestone
from events.forms import MilestoneCreateForm
from common.paginator import paginate

def timeline_list(request, project_slug, template_name='events/timeline_list.html'):
    project = get_object_or_404(Project, slug=project_slug)
    events = paginate(request, project.timeline_set.all())
    return render_to_response(template_name,
                              {'project': project,
                               'events': events},
                              context_instance=RequestContext(request))

def milestone_list(request, project_slug, template_name='events/milestone_list.html'):
    project = get_object_or_404(Project, slug=project_slug)
    milestones = paginate(request, project.milestone_set.all())
    return render_to_response(template_name, 
                              {'milestones': milestones,
                               'project': project,},
                               context_instance=RequestContext(request))

@transaction.commit_on_success
def create_milestone(request, project_slug, template_name='events/milestone_form.html'):
    project = get_object_or_404(Project, slug=project_slug)
    if request.method == 'POST':
        form = MilestoneCreateForm(request.POST)
        if form.is_valid():
            milestone = form.save(commit=False)
            milestone.project = project
            milestone.save()
            return HttpResponseRedirect(reverse('milestone_detail', args=[project.slug, str(milestone.id)]))
    else:
        form = MilestoneCreateForm()
    return render_to_response(template_name,
                              {'form': form,
                               'project': project},
                              context_instance=RequestContext(request))

def milestone_detail(request, project_slug, milestone_id, template_name='events/milestone_detail.html'):
    project = get_object_or_404(Project, slug=project_slug)
    milestone = get_object_or_404(Milestone, pk=milestone_id, project=project)
    return render_to_response(template_name,
                              {'milestone': milestone,
                               'project': project},
                              context_instance=RequestContext(request))
